package com.jdk.learn.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产消费者问题
 */
public class ProductAndConsumer {
    public static void main(String[] args) {
        User user=new User();
        Product product=new Product(user);
        Consumer consumer=new Consumer(user);
        product.start();
        consumer.start();
    }
}

class Product extends Thread {
    private User user;
    public Product(User user) {
        this.user=user;
    }

    @Override
    public void run() {
        int count=0;
        while (true) {
            if (count==0) {
                user.setUserName("老黄");
                user.setAge(20);
            }else{
                user.setUserName("老赵");
                user.setAge(50);
            }
            count=(count+1)%2;
//            System.out.println("count:"+count);
        }
    }
}

class Consumer extends Thread {
    private User user;
    public Consumer(User user) {
        this.user=user;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println(user);
        }
    }
}

class User {
    private String userName;
    private Integer age;
    //true时生产者等待 false时消费者等待
    public boolean flag=false;
    public Lock lock=new ReentrantLock();
    public Condition condition=lock.newCondition();

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
}